#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The cipher module provides encryption/decryption services
for tack modules.

    >>> from tack.lib.cipher import base64zip_encode, base64zip_decode, make_ciphers
    >>> base64zip_encode('ham&eggs')
    'eJzLSMxVS01PLwYADUUDAw=='

    >>> base64zip_decode('eJzLSMxVS01PLwYADUUDAw==')
    'ham&eggs'

    >>> e, d, c = make_ciphers()
    >>> ciphertext = e('ham&eggs')
    >>> base64zip_encode(ciphertext)
    'eJzTu7VDdIex0ue2b9vefN/gGU1vGgAud1T9'

    >>> cleartext = d(ciphertext)
    >>> cleartext
    'ham&eggs'

    >>> c(ciphertext, cleartext)
    True


"""

from Crypto.Cipher import Blowfish

enc_default_key = ('3VuwBz$8stNyYJBd!#i!%;Lh@z*2Vk&a'
                   'vCf(2:wB$[9Y$Qn%RjgiScY%iewz!dT8')


def base64zip_encode(val):
    return val.encode('zip').encode('base64')[0:-1]


def base64zip_decode(val):
    return (val+'\n').decode('base64').decode('zip')


def make_ciphers(key=enc_default_key, cipher=None, width=128, pad=' '):
    if cipher is None:
        cipher = Blowfish.new(key)

    def normalize(s):
        return s.rstrip()

    def encrypt(s):
        s = normalize(s).ljust(width, pad)[0:width]
        return cipher.encrypt(s)

    def decrypt(s):
        return cipher.decrypt(s).rstrip()

    def ciphercmp(ciphertext, cleartext):
        return decrypt(ciphertext) == normalize(cleartext)

    return (encrypt, decrypt, ciphercmp)


if __name__ == '__main__':
    encrypt, decrypt, cmpcrypt = make_ciphers("test")
    for passwd in ["foo", "bar", "baz", "barr ", "  baz  "]:
        p = decrypt(encrypt(passwd))
        print p, cmpcrypt(encrypt(passwd), p)

